package com.tangw.manage.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 
 * @author TangW
 *
 */
public class DBUtil {
	private static String url;
	private static String username;
	private static String password;
	private static String driverClass;

	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	static {
		Properties properties = new Properties();

		try (InputStream in = DBUtil.class.getClassLoader()
				.getResourceAsStream("config.properties")) {
			properties.load(in);
			url = properties.getProperty("url");
			username = properties.getProperty("username");
			password = properties.getProperty("password");
			driverClass = properties.getProperty("driverClass");
			Class.forName(driverClass);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		Connection connection = tl.get();
		if (connection == null) {
			try {
				connection = DriverManager.getConnection(url, username,
						password);
				tl.set(connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return connection;
	}

	public static void closeConnection() {
		Connection connection = tl.get();
		if (connection != null) {
			try {
				connection.close();
				tl.set(null);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
